let db = require("../db/index");
const bcrypt = require("bcryptjs");

// 获取头部导航条
exports.topBar = (req, res) => {
    let sql = "SELECT * FROM `article_type`";
    db.query(sql, (err, data) => {
        if (err) {
            return res.send({
                s: 400,
                m: "获取失败" + err,
            });
        }
        res.send({
            s: 200,
            data,
        });
    });
};
// 修改客户端用户信息
exports.setUserData = (req, res) => {
    let arr = req.body.arr;
    let sql = "UPDATE `user` SET `passname` = ? , `signature`= ? , `sex` = ? , `age` = ? WHERE account = ?";
    db.query(sql, arr, (err, data) => {
        if (err) {
            return res.send({
                s: 400,
                m: "修改失败" + err,
            });
        }
        res.send({
            s: 200,
            m: "修改成功",
        });
    });
};

// 添加喜欢/收藏
exports.addEssay = (req, res) => {
    let essayId = req.body.essayId;
    let userId = req.body.userId;
    let type = req.body.type;
    let sql1 = `select \`${type}\` from \`user\` where \`id\` = '${userId}' `;
    db.query(sql1, (err, data) => {
        if (err) {
            return res.send({
                s: 400,
                m: "添加失败",
            });
        }
        let arr = JSON.parse(data[0][type]);
        arr.push(essayId);
        str = JSON.stringify(arr);
        let sql2 = `UPDATE \`user\` SET \`${type}\` = ? WHERE \`id\` = ? `;
        db.query(sql2, [str, userId], (err, data) => {
            if (err) {
                return res.send({
                    s: 400,
                    m: "添加失败" + err,
                });
            }
            res.send({
                s: 200,
                m: "已添加",
            });
        });
    });
};
// 取消喜欢/收藏
exports.cancel = (req, res) => {
    let essayId = req.body.essayId;
    let userId = req.body.userId;
    let type = req.body.type;
    let sql1 = `select \`${type}\` from \`user\` where \`id\` = '${userId}' `;
    db.query(sql1, (err, data) => {
        if (err) {
            return res.send({
                s: 400,
                m: "取消失败",
            });
        }
        let arr = JSON.parse(data[0][type]);
        arr = arr.filter((i) => {
            return i != essayId;
        });
        str = JSON.stringify(arr);
        let sql2 = `UPDATE \`user\` SET ${type} = ? WHERE \`id\` = ?`;
        db.query(sql2, [str, userId], (err, data) => {
            if (err) {
                return res.send({
                    s: 400,
                    m: "取消失败",
                });
            }
            res.send({
                s: 200,
                m: "已取消",
            });
        });
    });
};
